import React, {useEffect, useState} from "react";

import style from './websocket.module.less'
import {Button, Form, Input, notification, Select} from "antd";
import {
    CheckCircleOutlined,
    DeleteColumnOutlined,
    DeleteFilled,
    PlayCircleOutlined,
    PlusCircleFilled, PlusCircleOutlined,
    PlusOutlined, SendOutlined
} from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import ClientForm from "./clientForm/clientForm";
import Chat from "./chat/chat";


export default function WebsocketTest() {
    const [formStatus, setFormStatus] = useState(false)
    const [deviceList, setDeviceList] = useState([]);
    const [selectedItem, setSelectedItem] = useState(null);
    const [form] = Form.useForm()
    const [formData, setFormData] = useState('')
    const [message, setMessage] = useState(null)
    const websocketMap = new Map()
    const formRules = {
        name: [
            {
                required: true,
                message: '请输入自定义名称!',
            },
        ],
        protocol: [
            {
                required: true,
                message: '请选择协议类型!',
            },
        ],
        address: [
            {
                required: true,
                message: '请输入服务地址!',
            },
        ],
        port: [
            {
                required: true,
                message: '请输入服务端口!',
            }
        ]
    }


    const connectDevice = () => {

    }


    const showAddDialog = () => {
        setFormStatus(!formStatus)
    }

    const addDevice = async (form) => {
        try {
            const result = await window.electronAPI.ws_InsertDevice(form);

            if (result) {
                notification.success({
                    message: '成功',
                    description: '设备添加成功！',
                    placement: 'topRight', // 提示框显示的位置
                });
            } else {
                notification.error({
                    message: '失败',
                    description: '设备添加失败，请重试。',
                    placement: 'topRight',
                });
            }
        } catch (error) {
            console.error('添加设备时出错:', error);
            notification.error({
                message: '错误',
                description: '设备添加失败，请重试。',
                placement: 'topRight',
            });
        }
    };

    const selectDeviceList = async () => {
        const deviceList = await window.electronAPI.ws_SelectDeviceList()
        console.log(deviceList)
        setDeviceList(deviceList)
    }
    const deleteDevice = (param) => {

    }
    const updateDevice = () => {

    }


    const selectWsMsgList = () => {

    }

    const deleteWsMsg = () => {

    }



    const sendMsg = () => {
        console.log('发送的消息', formData)
        const result = window.electronAPI.ws_msg_InsertMsg(formData)

        if (result){
            notification.open({
                message: '发送成功！',
                placement: 'topRight',
                duration: 3, // 通知显示的持续时间（秒）
            });
        }else{
            notification.error({
                message: '发送失败！',
                description: '请检查地址是否正确！',
                placement: 'topRight',
                duration: 3,
            })
        }
    }


    const changeWebsocket = (item) => {
        item.url = item.type + "://" + item.ip + ":" + item.port
        setSelectedItem(item)
        const result = window.electronAPI.changeWebsocket(item)
        if (result){
            notification.open({
                message: '连接成功！',
                description: `当前连接地址${item.url}`,
                placement: 'topRight',
                duration: 3, // 通知显示的持续时间（秒）
            });
        }else{
            notification.error({
                message: '连接失败！',
                description: '请检查地址是否正确！',
                placement: 'topRight',
                duration: 3,
            })
        }
    }




    useEffect(() => {
        selectDeviceList()
    }, [])

    return (
        <div className={style.container}>
            <div className={style.leftBox}>
                <div className={style.top}>
                    <span className={style.top__title}>WebSocket</span>
                    <Button icon={formStatus ? <SendOutlined/> : <PlusOutlined/>} className={style.top__button}
                            onClick={showAddDialog}/>
                </div>

                <div className={style.bottom}>
                    {deviceList.map(item => (
                        <div
                            key={item.ws_id}
                            className={`${style.deviceItem} ${selectedItem === item ? style['deviceItem--selected'] : ''}`}
                            onClick={() => changeWebsocket(item)}>
                            <div>
                                <Button style={{height: '30px', width: '30px', marginTop: '15px'}}
                                        icon={<CheckCircleOutlined style={{fontSize: 15}}/>} type={'text'}></Button>
                                <span>{item.type}{'://'}{item.ip}{":"}{item.port}</span>
                            </div>
                            <Button style={{height: '30px', width: '30px', marginTop: '15px'}}
                                    icon={<DeleteFilled style={{fontSize: 20}}/>} type={'dashed'}></Button>
                        </div>
                    ))}
                </div>
            </div>


            <div className={style.rightBox}>
                {
                    formStatus ? (
                        <div className={style.rightTop}>
                            <ClientForm />
                        </div>
                    ) : (
                        <div className={style.rightTop}>
                            <Chat/>
                        </div>
                    )
                }
                <div className={style.rightBottom}>

                    <TextArea rows={10} maxLength={100} showCount={true} placeholder={'请输入内容'}/>
                    <Button onClick={sendMsg} style={{float: 'right', margin: '20px 10px 0 0 '}}
                            type={'primary'}>发送（Enter）</Button>
                </div>
            </div>
        </div>
    )
}